require 'grammar'
require 'automata'

def grammar_to_automata(grammar)
    nonterms = {}
    nodes = []
    for rule in grammar.rules
        node = AutomataNode.new(rule.nonterm.name)
        nonterms[rule.nonterm] = node
        nodes << node
    end

    first = AutomataNode.new("0")
    first.add_edge(nonterms[grammar.start_nonterm])

    last = AutomataNode.new("F")

    nodes << first << last

    last.final = true

    for rule in grammar.rules
        case rule
        when FirstTypeRule
            first.add_edge(nonterms[rule.nonterm], rule.term)
        when SecondTypeRule
            nonterms[rule.nonterm].add_edge(nonterms[rule.nonterm2], rule.term)
        when ThirdTypeRule
            nonterms[rule.nonterm].add_edge(last)
        end
    end

    automata = Automata.new(nodes, first)
    return automata
end


term_a = Terminal.new("a")
term_b = Terminal.new("b")
nonterm_A = Nonterminal.new("A")

rule1 = FirstTypeRule.new(nonterm_A, term_a)
rule2 = FirstTypeRule.new(nonterm_A, term_b)
rule3 = ThirdTypeRule.new(nonterm_A)
rule4 = SecondTypeRule.new(nonterm_A, term_a, nonterm_A)

rules = []
rules << rule1 << rule2 << rule3 << rule4

grammar = Grammar.new(rules, nonterm_A)
grammar.print
automata = grammar_to_automata(grammar)

automata.print("output.dot")

puts(automata.parse("baaaa"))


